const multer = require("multer");
const MAO = require("multer-aliyun-oss");
const OSS = require("ali-oss");
const { BadRequest } = require("http-errors");
const path = require("path");

const isProd = process.env.NODE_ENV === "production";

// 阿里云配置信息
const config = {
  region: process.env.ALIYUN_REGION,
  accessKeyId: process.env.ALIYUN_ACCESS_KEY_ID,
  accessKeySecret: process.env.ALIYUN_ACCESS_KEY_SECRET,
  bucket: process.env.ALIYUN_BUCKET,
  secure: true, // 添加此行，强制使用 HTTPS
  endpoint: isProd
    ? "oss-cn-hangzhou-internal.aliyuncs.com"
    : "oss-cn-hangzhou.aliyuncs.com",
  internal: isProd, // 强制内网访问（某些SDK版本支持）
};
const configPrivate = {
  region: process.env.ALIYUN_REGION,
  accessKeyId: process.env.ALIYUN_ACCESS_KEY_ID,
  accessKeySecret: process.env.ALIYUN_ACCESS_KEY_SECRET,
  bucket: process.env.ALIYUN_BUCKET_PRIVATE,
  secure: true, // 添加此行，强制使用 HTTPS
  endpoint: isProd
    ? "oss-cn-hangzhou-internal.aliyuncs.com"
    : "oss-cn-hangzhou.aliyuncs.com",
  internal: isProd,
};

// 创建客户端时不使用自定义域名配置
const client = new OSS(config);

const uploadPublic = multer({
  storage: MAO({
    headers: {
      "Content-Disposition": "inline", // 添加这行，使浏览器直接预览
      "Cache-Control": "max-age=2592000", // 缓存 30 天
      "Content-Type": "image/jpeg", // 添加 Content-Type
    },
    options: {
      responseHeaders: {
        "Content-Disposition": "inline",
      },
    },
    config,
    destination: (req, file, cb) => {
      const folder = req.query.folder || "uploads";
      cb(null, folder);
    },
    filename: (req, file, cb) => {
      // 正确处理中文文件名
      const originalname = Buffer.from(file.originalname, "latin1").toString(
        "utf8"
      );
      const ext = path.extname(originalname);
      const timestamp = Date.now();
      const newFilename = `${path.basename(
        originalname,
        ext
      )}_${timestamp}${ext}`;
      cb(null, newFilename);
    },
  }),
  limits: {
    fileSize: 20 * 1024 * 1024, // 限制上传文件的大小为：20MB
  },
  fileFilter: function (req, file, cb) {
    // 只允许上传图片
    const fileType = file.mimetype.split("/")[0];
    const isImage = fileType === "image";

    if (!isImage) {
      return cb(new BadRequest("只允许上传图片。"));
    }

    cb(null, true);
  },
});

const uploadPrivate = multer({
  storage: MAO({
    headers: {
      "Content-Disposition": 'attachment; filename="file.jpg"',
    },
    config: configPrivate,
    destination: (req, file, cb) => {
      const folder = req.query.folder || "private-uploads";
      cb(null, folder);
    },
    filename: (req, file, cb) => {
      // 正确处理中文文件名
      const originalname = Buffer.from(file.originalname, "latin1").toString(
        "utf8"
      );
      const ext = path.extname(originalname);
      const timestamp = Date.now();
      const newFilename = `${path.basename(
        originalname,
        ext
      )}_${timestamp}${ext}`;
      cb(null, newFilename);
    },
  }),
  limits: {
    fileSize: 20 * 1024 * 1024, // 限制上传文件的大小为：20MB
  },
});

/**
 * 使用 http 请求头中的 content-length 限制文件大小
 * @param req
 * @param res
 * @param next
 * @returns {*}
 */
const fileSizeLimits = (req, res, next) => {
  const contentLength = parseInt(req.headers["content-length"]);
  // 限制上传文件的大小为：5MB
  if (contentLength > 100 * 1024 * 1024) {
    return next(new BadRequest("文件大小不能超过20MB"));
  }
  next();
};

/**
 * 单文件上传，指定表单字段名为 file
 * @param req
 * @param res
 * @param next
 */
const singleFileUpload = (req, res, next) => {
  // 检查文件大小是否超出限制
  fileSizeLimits(req, res, (err) => {
    if (err) return next(err);
    uploadPublic.single("file")(req, res, next);
  });
};

const singleFileUploadPrivate = (req, res, next) => {
  // 检查文件大小是否超出限制
  fileSizeLimits(req, res, (err) => {
    if (err) return next(err);
    uploadPrivate.single("file")(req, res, next);
  });
};

module.exports = {
  config,
  client,
  singleFileUpload,
  singleFileUploadPrivate,
};
